package com.fl.niu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fl.niu.dao.RolePermissionRelationDao;
import com.fl.niu.mapper.AdminRoleMapper;
import com.fl.niu.mapper.AdminRolePermissionRelationMapper;
import com.fl.niu.model.*;
import com.fl.niu.service.RoleService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 后台角色管理Service实现类
 * @author admin
 */
@Service
public class RoleServiceImpl extends ServiceImpl<AdminRoleMapper, AdminRole> implements RoleService {

    @Autowired
    private AdminRoleMapper roleMapper;
    @Autowired
    private AdminRolePermissionRelationMapper rolePermissionRelationMapper;
    @Autowired
    private RolePermissionRelationDao rolePermissionRelationDao;

    @Override
    public int create(AdminRole role) {
        role.setCreateTime(new Date());
        role.setAdminCount(0);
        role.setSort(0);
        return roleMapper.insert(role);
    }

    @Override
    public int update(Long id, AdminRole role) {
        role.setId(id);
        return roleMapper.updateById(role);
    }

    @Override
    public int delete(List<Long> ids) {
        int count = roleMapper.deleteBatchIds(ids);
        return count;
    }

    @Override
    public List<AdminPermission> getPermissionList(Long roleId) {
        return rolePermissionRelationDao.getPermissionList(roleId);
    }

    @Override
    @Transactional
    public int updatePermission(Long roleId, List<Long> permissionIds) {
        rolePermissionRelationMapper.delete(new QueryWrapper<AdminRolePermissionRelation>().eq("role_id",roleId));
        //批量插入新关系
        List<AdminRolePermissionRelation> relationList = new ArrayList<>();
        for (Long permissionId : permissionIds) {
            AdminRolePermissionRelation relation = new AdminRolePermissionRelation();
            relation.setRoleId(roleId);
            relation.setPermissionId(permissionId);
            relationList.add(relation);
        }
        return rolePermissionRelationDao.insertList(relationList);
    }


    @Override
    public List<AdminRole> list() {
        return roleMapper.selectList(new QueryWrapper<>());
    }

    @Override
    public List<AdminRole> list(String keyword, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        return roleMapper.selectList(new QueryWrapper<AdminRole>().like("name",keyword));
    }


}
